﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.Model.Enum;
using ServerControl.Utils;
using ServerControl.WebManage.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ServerControl.WebManage.Controllers.Admin
{
    [RoutePrefix("admin/user")]
    [Auth(AllowRole = Model.Enum.Role.Admin)]
    public class UserController : BaseController
    {
        private ILog logger = LogManager.GetLogger("UserController");

        [Route("index")]
        public ActionResult Index()
        {
            var scripts = ScriptDal.GetScripts();
            ViewBag.Scripts = scripts;
            UserDal.InitUsers();
            ViewBag.Commands = UserDal.GetCommands();
            return View();
        }

        [HttpPost]
        [Route("list")]
        public JsonResult UserList(string userName, int pageIndex = 1, int pageSize = 20, UserState userState = UserState.All, UserState expire = UserState.All)
        {
            try
            {
                var users = UserDal.GetList(pageIndex, pageSize, userState, expire, out int records, userName);
                users.ForEach(u =>
                {
                    u.Password = "";
                    u.Token = "";
                    u.Commands = UserDal.GetUserCommands(u.UserName);
                });
                return new JsonNetResult { Data = new SuccessResult<List<User>> { Data = users, Count = records, Msg = "", } };
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
        }

        [HttpPost]
        [Route("edit")]
        public JsonResult EditUser(User user, string action, List<int> commandIds)
        {
            try
            {
                var isSuccess = false;
                user.Remark = string.IsNullOrEmpty(user.Remark) ? string.Empty : user.Remark;

				if (action == "edit")
                {
                    if (!string.IsNullOrEmpty(user.Password))
                    {
                        user.Password = EncryptHelper.MD5Encrypt(user.Password);
                    }

                    isSuccess = UserDal.EditUser(user);
                }
                else
                {
                    user.IsEnable = true;
                    user.Role = Role.User;
                    user.AddTime = DateTime.Now;
                    user.LastLoginTime = DateTime.Now;
                    user.LastLoginIp = "";
                    user.Token = "";
                    user.Password = EncryptHelper.MD5Encrypt(user.Password);
                    isSuccess = UserDal.AddUser(user);
                }

                if (isSuccess)
                {
                    UserDal.UpdateCommands(user.UserName, commandIds);
                    return new JsonNetResult { Data = new SuccessResult { Msg = "操作成功", } };
                }
                else
                {
                    return new JsonNetResult { Data = new FailResult { Msg = "操作失败" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
        }

        [HttpPost]
        [Route("delete")]
        public JsonResult DeleteUser(string userName)
        {
            try
            {
                if (UserDal.DeleteUser(userName))
                {
                    return new JsonNetResult { Data = new SuccessResult { Msg = "删除成功", } };
                }
                else
                {
                    return new JsonNetResult { Data = new FailResult { Msg = "刪除失败" } };
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
        }

        [HttpPost]
        [Route("delete-users")]
        public JsonResult DeleteUsers(List<string> ids)
        {
            try
            {
                var result = UserDal.DeleteUsers(ids);
                return new JsonNetResult { Data = new SuccessResult { Msg = $"刪除共 {result} 位用户", } };
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
        }
    }
}